import json
import re
from typing import List, Dict, Tuple, Any
from core.client import APIClient
from config.settings import Config


class CourseService:
    """课程服务，处理课程相关的操作"""
    
    def __init__(self, client: APIClient):
        self.client = client
    
    def get_course_list(self) -> List[Dict[str, Any]]:
        """获取用户课程列表"""
        params = {
            'status': '',
            'type': '1',
        }
        
        response = self.client.get(Config.API_ENDPOINTS['course_list'], params=params)
        data = response.json()
        
        course_list = []
        for index, course in enumerate(data["data"]):
            course_info = {
                "userProductId": course["id"],
                "productName": course["productName"],
                "productCurriculumId": course["productCurriculumId"]
            }
            course_list.append(course_info)
            # print(f"序号{index}：{course_info}")
        
        return course_list
    
    def get_course_catalog(self, product_curriculum_id: str) -> Dict[str, Any]:
        """获取课程目录"""
        url = f"{Config.API_ENDPOINTS['course_catalog']}{product_curriculum_id}"
        response = self.client.get(url)
        return response.json()
    
    def extract_video_info(self, product_curriculum_id: str) -> List[Tuple[str, str]]:
        """从课程目录中提取视频信息"""
        catalog = self.get_course_catalog(product_curriculum_id)
        
        try:
            video_info_list = []
            course_nodes = catalog["data"]["courseNodes"]
            
            # 使用正则表达式提取视频名称和vid
            resource_names = re.findall(r"'resourceName': (.*?),", str(course_nodes), re.S)
            vid_list = re.findall(r"'vid': (.*?),", str(course_nodes), re.S)
            
            if len(resource_names) != len(vid_list):
                raise ValueError("匹配到的名称和vid数量不一致")
            
            for i in range(len(resource_names)):
                name = resource_names[i].replace("'", "").replace(".mp4", "")
                vid = vid_list[i].replace("'", "")
                
                if vid != 'None':
                    video_info_list.append((name, vid))
            
            return video_info_list
            
        except Exception as e:
            raise ValueError(f"提取视频信息失败：{e}")
    
    def save_course_info(self, product_name: str, product_curriculum_id: str, 
                        user_product_id: str, course_nodes: Dict[str, Any]):
        """保存课程信息到JSON文件"""
        course_nodes.update({
            'productName': product_name,
            'userProductId': user_product_id,
            'productCurriculumId': product_curriculum_id
        })
        
        filename = f"{product_name}_courseInfo.json"
        with open(filename, 'w', encoding=Config.ENCODING) as f:
            json.dump(course_nodes, f, ensure_ascii=False, indent=2)